//
//  OrderDetailCtrl.m
//  Traveling
//
//  Created by Northwan on 15/6/13.
//  Copyright (c) 2015年 长沙市岳麓区立早网络科技有限公司. All rights reserved.
//  旅游线路订单详情

#import "TravelLineOrderDetailCtrl.h"
#import "MineDataTool.h"
#import "OrderDetailRes.h"
#import "IPNPreSignMessageUtil.h"
#import "IpaynowPluginApi.h"
#import "AFHTTPRequestOperationManager.h"


#define kVCTitle          @"支付测试"
#define kBtnFirstTitle    @"获取订单，开始支付"
#define kWaiting          @"正在获取订单,请稍候..."
#define kNote             @"提示"
#define kConfirm          @"确定"
#define kErrorNet         @"网络错误"
#define kResult           @"支付结果："

@interface TravelLineOrderDetailCtrl ()<UIAlertViewDelegate,IpaynowPluginDelegate>
{
    NSString *_presignStr;
    UIAlertView* mAlert;
    NSMutableData* mData;
}
@property (weak, nonatomic) IBOutlet UILabel *orderStatusLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderDownTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderNumLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderAwayLabel;
@property (weak, nonatomic) IBOutlet UIImageView *productIconView;
@property (weak, nonatomic) IBOutlet UILabel *productNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *productAddressLabel;
@property (weak, nonatomic) IBOutlet UILabel *orderStateLabel;
@property (weak, nonatomic) IBOutlet UILabel *planBuyCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *relateUserLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (copy, nonatomic) NSString *order_sn;
@property (strong, nonatomic) OrderDetailRes *result;
@end

@implementation TravelLineOrderDetailCtrl

-(instancetype)initWithOrderSn:(NSString *)order_sn{
    self = [super init];
    if(self){
        self = [[TravelLineOrderDetailCtrl alloc]init];
        self.order_sn = order_sn;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"黄陂智慧旅游"];
    [self setupBottomPayBtn];
    [self requestData];
}

-(void)requestData{
    [MineDataTool getOrderDetailInfo:self.order_sn success:^(OrderDetailRes *result) {
        if(result.isSucc){
            [self inflateData:result];
        }else{
            [DialogUtils showTips:result.msg];
        }
    } failure:^(NSError *error) {
        [DialogUtils showTips:@"加载失败"];
    }];
}

-(void)setupBottomPayBtn{
    UIButton *payBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREENH-40-64, SCREENW, 40)];
    [payBtn setTitle:@"支付" forState:UIControlStateNormal];
    [payBtn setBackgroundImage:IMG(@"mine_paybtn_bg") forState:UIControlStateNormal];
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payBtn.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [payBtn addTarget:self action:@selector(tapPay) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:payBtn];
}



-(void)tapPay{
    NSLog(@"-------tapPay");
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    IPNPreSignMessageUtil *preSign=[[IPNPreSignMessageUtil alloc]init];
    preSign.appId=kNowPayAppId;
    preSign.mhtOrderNo=self.result.order_sn;
    preSign.mhtOrderName=self.result.goods_name;
    preSign.mhtOrderType=@"01";
    preSign.mhtCurrencyType=@"156";
    preSign.mhtOrderAmt=[NSString stringWithFormat:@"%.0f",[self.result.totalprice floatValue] *100];
    preSign.mhtOrderDetail=@"订单详情";
    preSign.mhtOrderStartTime=[dateFormatter stringFromDate:[NSDate date]];
    NSString *norifyUrl = [NSString  stringWithFormat:@"%@%@",BASE_URL,@"notify/appnoticeupdate.jspx"];
    preSign.notifyUrl= norifyUrl;
    preSign.mhtCharset=@"UTF-8";
    preSign.mhtOrderTimeOut=@"3600";
    preSign.mhtReserved=@"test";
    
    NSString *originStr =  [preSign generatePresignMessage];
    _presignStr = originStr;
    NSString *outputStr = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)originStr,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    NSLog(@"%@",outputStr);
    //开始准备网络请求
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:kAppValue forKey:kAppkey];
    [params setObject:outputStr forKey:@"paydata"];
    
    NSString *url = [NSString stringWithFormat:@"%@order/order_sign.json",BASE_URL];
    // 1.获得请求管理者
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
    [self showAlertWait];
    // 2.发送请求
    [mgr GET:url parameters:params
      success:^(AFHTTPRequestOperation *operation, id responseObj) {
          [self hideAlert];
          NSString *result =  [[NSString alloc]initWithData:responseObj encoding:NSUTF8StringEncoding];
          if(result){
               NSLog(@"success:%@",result);
               NSString* payData=[_presignStr stringByAppendingString:@"&"];
               payData=[payData stringByAppendingString:result];
              NSLog(@"%@",payData);
              [IpaynowPluginApi pay:payData AndScheme:@"IpaynowPluginTraveling" viewController:self delegate:self];
          }
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          [self hideAlert];
          [self showAlertMessage:kErrorNet];
          NSLog ( @"failure:%@" , error );
     }];
}

-(void)IpaynowPluginResult:(NSString*)result{
    NSMutableString *resultString = [[NSMutableString alloc] initWithString:kResult];
    [resultString appendString:result];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:kNote
                                                    message:resultString
                                                   delegate:nil
                                          cancelButtonTitle:kConfirm
                                          otherButtonTitles:nil];
    [alert show];
}
- (void)showAlertMessage:(NSString*)msg
{
    mAlert = [[UIAlertView alloc] initWithTitle:kNote message:msg delegate:nil cancelButtonTitle:kConfirm otherButtonTitles:nil, nil];
    [mAlert show];
}
- (void)showAlertWait {
    mAlert = [[UIAlertView alloc] initWithTitle:kWaiting message:nil delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [mAlert show];
    UIActivityIndicatorView* aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    aiv.center = CGPointMake(mAlert.frame.size.width / 2.0f - 15, mAlert.frame.size.height / 2.0f + 10 );
    [aiv startAnimating];
    [mAlert addSubview:aiv];
}

- (void)hideAlert {
    if (mAlert != nil)
    {
        [mAlert dismissWithClickedButtonIndex:0 animated:YES];
        mAlert = nil;
    }
}

-(void)inflateData:(OrderDetailRes *)result{
    self.result = result;
    if([@"pay" isEqualToString:result.pay]){
        [self.orderStatusLabel setText:@"已经支付"];
    }else{
        [self.orderStatusLabel setText:@"未支付"];
    }
    [self.orderDownTimeLabel setText:result.order_time];
    [self.orderNumLabel setText:result.order_sn];
    [self.orderPriceLabel setText:[NSString stringWithFormat:@"%@元",result.totalprice]];
    [self.orderAwayLabel setText:@"未支付"];
    [self.productIconView sd_setImageWithURL:[NSURL URLWithString:result.goods_img]];
    [self.productNameLabel setText:result.goods_name];
    [self.productAddressLabel setText:result.goods_address];
    if(result.state.intValue == 1){
        [self.orderStateLabel setText:@"交易不成功"];
    }else{
        [self.orderStateLabel setText:@"交易成功"];
    }
    [self.planBuyCountLabel setText:result.prenum];
    [self.relateUserLabel setText:result.pre_username];
    [self.phoneLabel setText:result.pre_mobile];
}



/*
 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response {
 NSHTTPURLResponse* rsp = (NSHTTPURLResponse*)response;
 int code = (int)[rsp statusCode];
 if (code != 200) {
 } else {
 if (mData != nil) {
 mData = nil;
 }
 mData = [[NSMutableData alloc] init];
 }
 }
 
 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
 [mData appendData:data];
 }
 
 - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
 [self hideAlert];
 NSString* data = [[NSMutableString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
 NSString* payData=[_presignStr stringByAppendingString:@"&"];
 payData=[payData stringByAppendingString:data];
 [IpaynowPluginApi pay:result AndScheme:@"IpaynowPluginDemo" viewController:self delegate:self];
 }
 
 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
 [self hideAlert];
 [self showAlertMessage:kErrorNet];
 }
 */

@end
